#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <unistd.h>



#define BUFFER_SIZE 1024

int main(int argc, char const *argv[])
{
    int server_fd, client_fd;
    struct sockaddr_in server_addr, cli_addr;
    socklen_t cliaddr_len = sizeof(cli_addr);
    int backlog = 5;
    int server_port = 7093;
    char *buffer = (char *)malloc(BUFFER_SIZE);

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);


    // AF_INET ipv4协议
    // SOCK_STREAM tcp协议
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0)
    {
        perror("socket init failed");
        exit(EXIT_FAILURE);
    }



    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
    {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    if (listen(server_fd, backlog) < 0)
    {
        perror("listen failed");
        exit(EXIT_FAILURE);
    }

    while (1) {
        client_fd = accept(server_fd, (struct sockaddr *)&cli_addr, &cliaddr_len);
        if (client_fd < 0)
        {
            perror("accept failed");
            continue;
        }
        printf("accepted client %d\n", client_fd);

        int bytes_read = recv(client_fd, buffer, BUFFER_SIZE - 1, 0);
        if (bytes_read > 0) {
            buffer[bytes_read] = '\0';
            printf("received %d bytes: %s\n", bytes_read, buffer);
        }
        const char *response =
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: text/plain\r\n"
        "Content-Length: 13\r\n"
        "\r\n"
        "Hello, World!";

        send(client_fd, response, strlen(response), 0);
        close(client_fd);
    }

    // close
    close(client_fd);
    close(server_fd);
    return 0;
}
